package com.zzzzzz.content.topictag;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.core.dao.BaseDao;

@Repository
public class TopicTagDao extends BaseDao{
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private final static String ADD = 							"insert into topic_tag(topic_id, tag_id) values(?, ?)";
	private final static String DEL_BY_TOPICID = 				"delete from topic_tag where topic_id = ?";
	private final static String DEL_BY_TOPICID_AND_TAGID = 		"delete from topic_tag where topic_id = ? and tag_id = ?";
	private final static String FIND_TAGNAME_BY_TOPICID = 		"select t.name from topic_tag tt inner join tag t on tt.tag_id = t.id where tt.topic_id = ? and t.status = 0 and (t.up_id is null or t.up_id <> 0)";
	
	public void add(TopicTag topicTag){
		jdbcTemplate.update(ADD, topicTag.getTopicId(), topicTag.getTagId());
	}
	
	public void delByTopicId(Long topicId){
		jdbcTemplate.update(DEL_BY_TOPICID, topicId);
	}
	
	public void delByTopicIdAndTagId(Long topicId, Integer tagId){
		jdbcTemplate.update(DEL_BY_TOPICID_AND_TAGID, topicId, tagId);
	}
	
	public List<String> findTagNameByTopicId(Long topicId){
		return jdbcTemplate.query(
				FIND_TAGNAME_BY_TOPICID, 
				new RowMapper<String>(){
					public String mapRow(ResultSet rs, int rn)
							throws SQLException {
						return rs.getString("name");
					}
				}, 
				topicId);
	}
	
}
